package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Offer;
import softswitch.model.OfferGroup;


@Stateless
public class OfferDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Offer getById(Integer id){	
		return  em.find(Offer.class, id);
	}
    
    public Offer save(Offer offer) {
    	em.persist(offer); 
    	return offer;
    }
    
    public Offer update(Offer offer) {
    	return em.merge(offer); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Offer.class, id));	
    }
    	
	@SuppressWarnings("unchecked")
    public List<Offer> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Offer e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    //--------------------------------------------------------
    
    @SuppressWarnings("unchecked")
    public List<Offer> listByOfferGroup(OfferGroup offergroup) {    	
    	Query query = em.createQuery("SELECT e FROM Offer e WHERE e.offergroup=:offergroup");
    	query.setParameter("offergroup", offergroup);
    	return query.getResultList();   
    }
    
    
}

